import { Card as SemiCard, ButtonGroup, Button } from "@douyinfe/semi-ui";
import { IconRefresh } from "@douyinfe/semi-icons";
import { useEffect } from "react";
import { useModel } from "umi";
import { useReactive } from "ahooks";
import OrgTree from "react-org-tree";
import { Card, message, Row, Col, Spin, Space, Form, Select, Radio, Tag, Modal } from "antd";
import { CloseCircleOutlined } from "@ant-design/icons";

import useAllMembers from "../hooks/member/useAllMembers";
import useAllMemberStructuresToTree from "../hooks/member/useAllMemberStructuresToTree";
import useDeleteMemberStructure from "../hooks/member/useDeleteMemberStructure";
import useAddMemberStructure from "../hooks/member/useAddMemberStructure";

const MemberStructurePage = () => {
    const { windowInnerHeight } = useModel("global");
    const { organizationInfo } = useModel("organization.info");

    const { loading, isShowTree, loadAllMembersStructuresToTree, memberStructuresTree, memberStructures } = useAllMemberStructuresToTree();
    const { loading: deleteLoading, deleteMemberStructure } = useDeleteMemberStructure();

    const state = useReactive({
        selectNode: {},
        horizontal: false,
    });

    const removeNode = async (record) => {
        Modal.confirm({
            title: "确认",
            content: `确认要移除[${record.omName}]该人员信息吗?`,
            okButtonProps: { loading: deleteLoading },
            onOk: async () => {
                let res = await deleteMemberStructure(record.omUuid);
                if (res) {
                    message.success("成功移除人员信息");
                    loadAllMembersStructuresToTree();
                }
            },
        });
    };

    const renderContent = (data) => {
        return data.type !== "person" ? (
            <div key={data.id} style={{ textAlign: "center", padding: 10, color: state.selectNode.id === data.id ? "yellow" : "#000" }}>
                {data.name}
            </div>
        ) : (
            <div
                key={data.id}
                style={{ textAlign: "center", position: "relative", backgroundColor: state.selectNode.id === data.id ? "#eee" : "#fff", width: "auto", padding: 10 }}
            >
                <div style={{ position: "absolute", right: -6, top: -6, visibility: !data.children ? "visible" : "hidden" }}>
                    <CloseCircleOutlined style={{ color: "red" }} onClick={() => removeNode(data)} />
                </div>
                <Space style={{ textAlign: "center" }}>
                    <Space direction="vertical" size={0} style={{ fontSize: 12 }}>
                        <div style={{ fontSize: 15, fontWeight: 600 }}>{data.name}</div>
                        <div>{data.omPosi || "-"}</div>
                    </Space>
                </Space>
                <div style={{ marginTop: 5 }}>
                    <Space size={2}>
                        <Tag color={data.isAudt ? "#f50" : "gray"} style={{ margin: 0 }}>
                            核
                        </Tag>
                        <Tag color={data.isAppr ? "#f50" : "gray"} style={{ margin: 0 }}>
                            批
                        </Tag>
                    </Space>
                </div>
            </div>
        );
    };

    const cardBodyHeight = windowInnerHeight - 90 - 20 - 48;

    return (
        <Row gutter={10}>
            <Col span={18}>
                <SemiCard
                    title={<span style={{ lineHeight: "32px", fontSize: 15 }}>成员架构</span>}
                    headerStyle={{ padding: "7px 12px" }}
                    headerExtraContent={
                        <Space>
                            <Radio.Group
                                options={[
                                    { label: "竖向", value: false },
                                    { label: "横向", value: true },
                                ]}
                                onChange={({ target: { value } }) => (state.horizontal = value)}
                                value={state.horizontal}
                                optionType="button"
                                buttonStyle="solid"
                            />
                            <Button icon={<IconRefresh />} onClick={loadAllMembersStructuresToTree}></Button>
                        </Space>
                    }
                    shadows="always"
                    bordered={false}
                    bodyStyle={{ padding: 0, height: cardBodyHeight, overflow: "auto", textAlign: "center" }}
                >
                    <Spin spinning={loading}>
                        {isShowTree && (
                            <OrgTree
                                data={memberStructuresTree}
                                horizontal={state.horizontal}
                                collapsable={true}
                                expandAll={true}
                                renderContent={renderContent}
                                // onClick={(e, data) => (state.selectNode = data)}
                            />
                        )}
                    </Spin>
                </SemiCard>
            </Col>
            <Col span={6}>
                <SemiCard
                    title={<span style={{ lineHeight: "32px", fontSize: 15 }}> {organizationInfo.fullName || "-"} </span>}
                    headerStyle={{ padding: "7px 12px" }}
                    headerExtraContent={<ButtonGroup theme="borderless"></ButtonGroup>}
                    shadows="always"
                    bordered={false}
                    bodyStyle={{ padding: 0, height: cardBodyHeight }}
                >
                    <Space direction="vertical" size={10} style={{ padding: "10px 16px", width: "100%" }}>
                        <Card title="人员设置" bordered={true} size="small">
                            <MemberSetting memberStructures={memberStructures} reloadData={loadAllMembersStructuresToTree} />
                        </Card>
                    </Space>
                </SemiCard>
            </Col>
        </Row>
    );
};

const MemberSetting = ({ memberStructures, reloadData }) => {
    const [form] = Form.useForm();

    const { members } = useAllMembers();
    const { loading: addLoading, addMemberStructure } = useAddMemberStructure();

    const state = useReactive({
        selectedMember: null,
        selectedParent: null,
        selectOptions: [],
    });

    useEffect(() => {
        form.setFieldValue("paUuid", undefined);
        if (state.selectedMember?.omUuid) {
            state.selectOptions = memberStructures.filter((item) => item.omUuid !== state.selectedMember.omUuid && !item.paPath.includes(state.selectedMember.omUuid));
        }
    }, [state.selectedMember]);

    let onFinish = async (values) => {
        let index = memberStructures.findIndex((item) => item.omUuid === state.selectedMember?.omUuid);

        if (state.selectedParent) {
            values.omLeve = state.selectedParent.omLeve + 1;
            values.paPath = Array.from(new Set([state.selectedParent.omUuid].concat(state.selectedParent.paPath)));
        } else {
            values.omLeve = 1;
            values.paPath = [];
            values.paUuid = null;
        }

        let res = await addMemberStructure(values, index === -1 ? "create" : "update");
        if (res) {
            message.success("成功设置人员信息");
            reloadData();
            form.resetFields();
        }
    };

    return (
        <Form form={form} layout="vertical" onFinish={onFinish}>
            <Form.Item label="选择人员" name="omUuid" rules={[{ required: true, message: "请选择" }]}>
                <Select
                    showSearch
                    allowClear
                    placeholder="选择人员"
                    onChange={(value, option) => (state.selectedMember = option)}
                    filterOption={(input, option) => (option?.omName ?? "").includes(input)}
                    fieldNames={{ label: "omName", value: "omUuid" }}
                    options={members}
                />
            </Form.Item>

            <Form.Item label="选择上级" name="paUuid" rules={[{ required: false, message: "请选择" }]}>
                <Select
                    showSearch
                    allowClear
                    placeholder="选择上级"
                    onChange={(value, option) => (state.selectedParent = option)}
                    filterOption={(input, option) => (option?.omName ?? "").includes(input)}
                    fieldNames={{ label: "omName", value: "omUuid" }}
                    options={state.selectOptions}
                />
            </Form.Item>

            <Form.Item label="审核权利" name="isAudt" rules={[{ required: true, message: "请选择" }]}>
                <Radio.Group>
                    <Radio value={true}>有</Radio>
                    <Radio value={false}>无</Radio>
                </Radio.Group>
            </Form.Item>

            <Form.Item label="审批权利" name="isAppr" rules={[{ required: true, message: "请选择" }]}>
                <Radio.Group>
                    <Radio value={true}>有</Radio>
                    <Radio value={false}>无</Radio>
                </Radio.Group>
            </Form.Item>

            <div style={{ marginTop: 20, textAlign: "center" }}>
                <Space>
                    <Button loading={addLoading} type="primary" theme="solid" htmlType="submit" style={{ width: "100%" }}>
                        提交
                    </Button>
                    <Button loading={addLoading} onClick={() => form.resetFields()}>
                        重置
                    </Button>
                </Space>
            </div>
        </Form>
    );
};

export default MemberStructurePage;
